#include "PrecompiledHeader_FileSysMgr.h"
#include "DataSource.h"

/*--------------------------------------------------------------------------*/

DataSource::DataSource(const std::string& path) :
	m_path(path)
{

}

/*--------------------------------------------------------------------------*/

DataSource::~DataSource()
{

}

/*--------------------------------------------------------------------------*/

const std::string& DataSource::GetPath() const
{
	return this->m_path;
}

/*--------------------------------------------------------------------------*/

void DataSource::UpdateAll()
{
	this->UpdateRec(this->m_path);
}

/*--------------------------------------------------------------------------*/

void DataSource::UpdateRec( const std::string& path )
{
    HANDLE dir;
    WIN32_FIND_DATA file_data;

    if ((dir = FindFirstFile((path + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
	{
        return;
	}

    do 
	{
        const std::string file_name = file_data.cFileName;
        const std::string full_file_name = path + "/" + file_name;
        const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

        if (file_name[0] == '.')
            continue;

        if (is_directory)
		{
			this->UpdateRec(full_file_name);
            continue;
		}

		this->RegisterFile(full_file_name);
    } 
	while (FindNextFile(dir, &file_data));

    FindClose(dir);
}

/*--------------------------------------------------------------------------*/

void DataSource::RegisterFile( const std::string& filepath )
{
	AssertLogI(true, "Registering %s", filepath.c_str());
	FileDesc file(filepath, this);
	
	IFiletype* loadedfile = FileSys::RegisterFile(&file);

	this->m_files[file.GetFullname()] = loadedfile;
}

/*--------------------------------------------------------------------------*/

IFiletype* DataSource::GetFile( const std::string& name )
{
	auto file = this->m_files.find(name);

	if (file != this->m_files.end())
	{
		return file->second;
	}
	else
	{
		return NULL;
	}
}

/*--------------------------------------------------------------------------*/

const std::map<std::string, IFiletype*>& DataSource::GetFilesList() const
{
	return this->m_files;
}

/*--------------------------------------------------------------------------*/